<!DOCTYPE html>
<head>
    <meta charset="utf-8" />
    <!-- 移动设备支持 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
</head>

<style>
    /**重置标签默认样式*/
    * {
        margin: 0;
        padding: 0;
        list-style: none;
        font-family: '微软雅黑'
    }
    #container {
        width: 100%;
        height: 100%;
        background: #eee;
        position: relative;
    }
    .header {
        width: 100%;
        height: 50px;
        color: #fff;
        background: #999999;
        line-height: 50px;
        font-size: 20px;
        position: fixed;
        padding: 0 100px 0px 0px;
        top: 0px;
    }
    .footer {
        width: 100%;
        height: 50px;
        background: #999999;
        position: fixed;
        bottom: 0;
        padding-top: 10px;
        padding-bottom: 10px;
    }
    .footer input {
        width: 75%;
        height: 45px;
        outline: none;
        font-size: 20px;
        text-indent: 10px;
        position: absolute;
        border-radius: 6px;
        left:3%;
    }
    .footer span {
        display: inline-block;
        width: 15%;
        height: 48px;
        background: #ccc;
        font-weight: 900;
        line-height: 45px;
        cursor: pointer;
        text-align: center;
        position: absolute;
        right: 3%;
        border-radius: 6px;
    }

    .content {
        font-size: 20px;
        width: 100%;
        overflow: auto;
        margin-top:50px;
        margin-bottom: 70px;
    }
    .content li {
        margin-top: 10px;
        width: 100%;
        display: block;
        clear: both;
        overflow: hidden;
    }
    .content li span{
        background: #7cfc00;
        padding: 10px;
        border-radius: 10px;
        margin: 6px 10px 0 10px;
        max-width: 310px;
        border: 1px solid #ccc;
        box-shadow: 0 0 3px #ccc;
    }
    .imgleft {
        float: left;
        margin-left: 5px;
    }
    .imgright {
        float: right;
        margin-right: 5px;
    }
    .spanleft{
        float: left;
        background: #fff;
    }
    .spanright {
        float: right;
        background: #7cfc00;
    }
    /*加载数据时隐藏源代码*/
    [v-cloak] {
        display: none;
    }
</style>
<html>
<body>
    <div id="container">
        <div class="header">
            <span onclick="jump()" style="float:left;width: 12%"><img src="/image/left.png" style="height: 50px;"/></span>
            <div id="targetId" style="float:left;text-align: center;line-height: 50px;width: 76%;" v-cloak>{{ targetName }}</div>
            <div style="float:left;width: 12%;height: 50px;"></div>
        </div>
        <ul class="content">
            <li style=""></li>
        </ul>
        <div class="footer">
            <input id="text" type="text" placeholder="说点什么吧...">
            <span id="btn">发送</span>
        </div>
    </div>
</body>

</html>

<script type="text/javascript" src="/js/chat/dataUtil.js" ></script>
<script type="text/javascript" src="/js/chat/rongCloud.js" ></script>
<script type="text/javascript" src="/js/chat/rongConfig.js" ></script>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script src="https://cdn.ronghub.com/RongIMLib-2.2.5.min.js"></script>
<script type="text/javascript">
    window.onload = initRong();
    var rongCloud = new RongCloud();
    //初始化融云服务,并启动消息监听
    function initRong(){
        var rongCloud = new RongCloud();
        var rongConfig = new RongConfig();
        rongCloud.initRong(rongConfig.getAppkey());
        //用户登录rong
        loginRong();
        getUserInfo();
        //初始化页面
        pageInit();
        //把要清空的对象id存放到缓存
        localStorage.setItem("closeId","<?php echo $targetId ?>");
    }

    /**
     * 把用户头像姓名存放到缓存
     */
    function getUserInfo() {
        //获取对方的id和自己的id
        var targetIdAndSendId = localStorage.getItem("userId") + "," + "<?php echo  $targetId?>";
        //先用加姓名头像 25 24 用户的  25 是自己的id 24使目标id
        //var targetIdAndSendId = "oHNCGjmOMyk87ACKZrZ_A1CEiagA,oHNCGjrgAym1xXiAWsPJfXPChTk4";
        // 获取用户信息
        $.ajax({
            type: "get",
            url: "/api/mobile/agentService/getUserInfoByOpenId",
            dataType: "text",
            data: {openIds:targetIdAndSendId},
            success: function(ret, err) {
                //用户信息
                ret = $.parseJSON(ret);
                if(ret.resultCode == 1) {
                    //vue渲染数据到页面
                    var header = new Vue({
                        el: '.header',
                        data: {
                            targetName: ret.extend[1].nickName,
                        },
                    })
                    //把用户头像存放到缓存
                    localStorage.setItem("userImgUrl", ret.extend[0].headImgUrl);
                    localStorage.setItem("targetImgUrl",ret.extend[1].headImgUrl);

                } else {
                    alert("获取用户头像失败！");
                }
            },
            error:function(){
                $('#content_empty').show();
            }
        });
    }

    /**
     * 登录时获取历史消息
     */
    function loginRong() {
        //获取用户token
        var token = "<?php echo $token ?>";
        var rongCloud = new RongCloud();
        rongCloud.connectSession(function(status,userId){
            if(status) {
                //把自己的token和userId存放到缓存
                localStorage.setItem("token", token);
                localStorage.setItem("userId",userId);
                //初始化时获取用户历史消息3-10条
                var targetIdPar = "<?php echo $targetId ?>";
                var countPar = "<?php echo $count ?>";
                getHistory(targetIdPar,parseInt(countPar),0);
            }else {
                alert("登录失败！");
            }

        },token);
    }

    /**
     * 初始化融云 和 页面数据渲染
     */
    //定义自己的头像地址 和 别人的头像存放
    function pageInit(){
        var userInfo = {};
        var btn = document.getElementById('btn');
        var text = document.getElementById('text');
        var content = document.getElementsByTagName('ul')[0];

        //一定要设置高度才能把数据实时的放在最下面 高度为屏幕分辨率的高减去上下div的高度 上50px 下70px
        //还要减去减去初始化3条信息的高度150 网页才能兼容  ix下面会多出一部分不兼容
        content.style.height=window.screen.height-120+"px";
        btn.onclick = function(){
            if(text.value.replace(/\s+/g,"") == '') {
                alert("不能发送空白消息");
                text.value = '';
                return;
            }else {
                writeInContent(0,text.value,"<?php echo $targetId?>",'');
                // 内容过多时,将滚动条放置到最底端
                content.scrollTop = content.scrollHeight;
                //sendGroupChat(text.value);
                sendMessage("<?php echo  $targetId?>", text.value);
                text.value = '';
            }
        }
    }

    /**
     * 写入数据到content
     * writeFormat 写入在左还是右 0右 1左
     * contentText 写入内容
     * list 为空表示是单条插入到最底部，为集合表示多条插入到最顶部
     */
    function writeInContent(num,contentText,closeId,list) {
        var content = document.getElementsByTagName('ul')[0];
        var str = '';
        for(var i in list) {
            //如果发送人时自己那么就显示到右边
            if (list[i].senderUserId == localStorage.getItem("userId")) {
                str += '<li><img class="imgright" src="'+localStorage.getItem('userImgUrl')+'" width="50px" height="50px"><span class="spanright">'+list[i].content.content+'</span></li>';
            } else {
                str += '<li><img class="imgleft" src="'+localStorage.getItem('targetImgUrl')+'" width="50px" height="50px"><span class="spanleft">'+list[i].content.content+'</span></li>';
            }
        }
        if(list == '') {
            if(num==0){
                str = '<li><img class="imgright" src="'+localStorage.getItem("userImgUrl")+'" width="50px" height="50px"><span class="spanright">'+contentText+'</span></li>';
            }else {
                str = '<li><img class="imgleft" src="'+localStorage.getItem("targetImgUrl")+'" width="50px" height="50px"><span class="spanleft">'+contentText+'</span></li>';
            }
            content.innerHTML += str;
        }else {
            $(content).prepend(str);
        }
    }

    //var xfjApiUrl = '<?php echo WX_XFJ_API_URL ?>';
    function sendMessage(targetId,contentText) {
        rongCloud.sendMessage(targetId,contentText,"");

        /*//发送消息
        var agentId = localStorage.getItem("userId");
        agentId = agentId+"";
        targetId = targetId+"";
        $.ajax({
            type: "post"
            ,url:xfjApiUrl+"/mobile/wx_chat/publishMessage"
            //,url:"http://192.168.10.181:9091/api/mobile/chatService/publishMessage"
            ,data: {fromUserId:agentId,toUserId:targetId,content:contentText}
            ,datatype:'text'
            ,success:function(data){
                //发送成功后...
            }

            ,timeout:20000
        })*/
    }



    /**
     * 获取和莫个人的聊天记录 并调用写入数据到congten得方法
     * @param targetIdPar 和谁的记录
     * @param countPar 查询几条
     * @param mode 方式 1 为点击加载更多 0为初始化查询
     * @return hasMag 真表示还有数据
     */
    function getHistory(targetIdPar,countPar,mode){
        if (mode == 1) { //点击获取历史消息的时候删除一下加载更多这几个字
            $(".jzgd").empty();
        }
        var rongCloud = new RongCloud();
        var conversationType = RongIMLib.ConversationType.PRIVATE; //私聊,其他会话选择相应的消息类型即可。
        var targetId= targetIdPar+""; // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。 字符串类型
        var timestrap = null; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0; int
        var count = parseInt(countPar); // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。 int性
        if(1 >= count){ //小于等于1报错 仿qq0的时候查3条
            count = 3;
        }
        if(count >= 20) { //超过二十报错 那么就不让他超过20条
            count = 20;
        }

        rongCloud.getHistoryById(function (hasMag, list) {
            writeInContent('','',"<?php echo $targetId ?>",list);
            if(parseInt(countPar) != 4 ) { //第一次获取的历史消息数和传过来的未读消息数相同是hasMag还是为true

            }
                if(hasMag){
                var rowsDisplayed = 10; //查询历史消息每次多加载十条数据
                //加载更多 //onclick=\"getHistory("+targetIdPar+","+null+","+20+")\"
                targetIdPar = "'"+targetIdPar+"'";
                var jzgd = "<li class='jzgd' onclick=\"getHistory("+targetIdPar+","+rowsDisplayed+","+1+")\" style='text-align: center;font-size: 16px;color:#4EA9E9'>查看更多消息</li>";
                $(".content").prepend(jzgd);
            }

        },conversationType,targetId, timestrap, count);
    }

    /**
     * 清空消息数 要清空必须得
     * 在这个页面获取一下历史消息才能永久成功
     */
    function closeMessageCount(closeId) {
        var rongCloud = new RongCloud();
        rongCloud.getHistoryById(function (hasMag, list) {
            //清空数据
            rongCloud.cleanMessageCount(localStorage.getItem("closeId"));
        },RongIMLib.ConversationType.PRIVATE,localStorage.getItem("closeId"), null, 20);
    }

    /**
     * 跳转到会话页面
     */
    function jump(){
        window.location.href = "/mobile/wx_chat/conversationPage";
    }
</script>